Page({
  data: {
    studyRecords: [], // 学习记录列表
    statsPeriod: 'all', // 统计周期：week/month/all
    currentStats: {
      totalDays: 0,
      totalWords: 0,
      totalTime: 0,
      accuracy: 0
    },
    achievements: [
      {
        id: 1,
        name: '初学者',
        desc: '完成第一次学习',
        icon: '/images/star.png',
        unlocked: false,
        condition: 'firstStudy'
      },
      {
        id: 2,
        name: '坚持者',
        desc: '连续学习7天',
        icon: '/images/star-filled.png',
        unlocked: false,
        condition: 'consecutive7'
      },
      {
        id: 3,
        name: '词汇达人',
        desc: '累计学习100个单词',
        icon: '/images/word.png',
        unlocked: false,
        condition: 'words100'
      },
      {
        id: 4,
        name: '精确射手',
        desc: '单次学习正确率达到90%',
        icon: '/images/star-filled.png',
        unlocked: false,
        condition: 'accuracy90'
      }
    ]
  },

  onLoad: function(options) {
    this.loadStudyRecords();
    this.updateAchievements();
    
    // 如果没有记录，创建一些测试数据便于演示
    const records = wx.getStorageSync('studyRecords') || [];
    if (records.length === 0) {
      this.createTestData();
    }
  },

  onShow: function() {
    this.loadStudyRecords();
    this.updateAchievements();
  },

  // 加载学习记录
  loadStudyRecords: function() {
    const records = wx.getStorageSync('studyRecords') || [];
    
    // 按日期倒序排列
    const sortedRecords = records.sort((a, b) => {
      return new Date(b.timestamp || b.date) - new Date(a.timestamp || a.date);
    });

    this.setData({
      studyRecords: sortedRecords
    });

    this.calculateStats();
  },

  // 计算统计数据
  calculateStats: function() {
    const { studyRecords } = this.data;

    // 计算统计数据
    const totalWords = studyRecords.reduce((sum, record) => {
      return sum + (record.wordsLearned || 0);
    }, 0);
    
    const totalTime = studyRecords.reduce((sum, record) => {
      return sum + (record.duration || 0);
    }, 0);
    
    const totalCorrect = studyRecords.reduce((sum, record) => {
      const words = record.wordsLearned || 0;
      const rate = record.correctRate || 0;
      const correct = Math.round(words * rate / 100);
      return sum + correct;
    }, 0);
    
    // 计算学习天数（去重日期）
    const studyDates = new Set();
    studyRecords.forEach(record => {
      if (record.timestamp) {
        const date = new Date(record.timestamp);
        const dateKey = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
        studyDates.add(dateKey);
      }
    });
    
    const totalDays = studyDates.size;
    const accuracy = totalWords > 0 ? Math.round((totalCorrect / totalWords) * 100) : 0;

    this.setData({
      currentStats: {
        totalDays,
        totalWords,
        totalTime,
        accuracy
      }
    });
  },

  // 切换统计周期
  changePeriod: function(e) {
    const period = e.currentTarget.dataset.period;
    this.setData({
      statsPeriod: period
    });
    this.calculateStats();
  },

  // 删除单条记录
  deleteRecord: function(e) {
    const index = e.currentTarget.dataset.index;
    const record = this.data.studyRecords[index];
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除${record.date}的学习记录吗？`,
      success: (res) => {
        if (res.confirm) {
          this.removeRecord(index);
        }
      }
    });
  },

  // 执行删除记录
  removeRecord: function(index) {
    const records = [...this.data.studyRecords];
    records.splice(index, 1);
    
    // 更新本地存储
    wx.setStorageSync('studyRecords', records);
    
    this.setData({
      studyRecords: records
    });
    
    this.calculateStats();
    this.updateAchievements();
    
    wx.showToast({
      title: '删除成功',
      icon: 'success'
    });
  },

  // 清空所有记录
  clearAllRecords: function() {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空所有学习记录吗？此操作无法恢复。',
      confirmColor: '#ff4444',
      success: (res) => {
        if (res.confirm) {
          this.clearRecords();
        }
      }
    });
  },

  // 执行清空操作
  clearRecords: function() {
    wx.setStorageSync('studyRecords', []);
    
    this.setData({
      studyRecords: [],
      currentStats: {
        totalDays: 0,
        totalWords: 0,
        totalTime: 0,
        accuracy: 0
      }
    });
    
    this.updateAchievements();
    
    wx.showToast({
      title: '清空成功',
      icon: 'success'
    });
  },

  // 更新成就状态
  updateAchievements: function() {
    const { studyRecords } = this.data;
    let { achievements } = this.data;
    
    achievements = achievements.map(achievement => {
      let unlocked = false;
      let progress = '';
      
      switch (achievement.condition) {
        case 'firstStudy':
          unlocked = studyRecords.length > 0;
          progress = unlocked ? '' : '完成首次学习';
          break;
          
        case 'consecutive7':
          const consecutiveDays = this.getConsecutiveDays();
          unlocked = consecutiveDays >= 7;
          progress = unlocked ? '' : `${consecutiveDays}/7天`;
          break;
          
        case 'words100':
          const totalWords = studyRecords.reduce((sum, record) => sum + (record.wordsLearned || 0), 0);
          unlocked = totalWords >= 100;
          progress = unlocked ? '' : `${totalWords}/100个`;
          break;
          
        case 'accuracy90':
          const hasHighAccuracy = studyRecords.some(record => (record.correctRate || 0) >= 90);
          unlocked = hasHighAccuracy;
          progress = unlocked ? '' : '单次达到90%正确率';
          break;
      }
      
      return {
        ...achievement,
        unlocked,
        progress
      };
    });
    
    this.setData({
      achievements
    });
  },

  // 计算连续学习天数
  getConsecutiveDays: function() {
    const { studyRecords } = this.data;
    if (studyRecords.length === 0) return 0;
    
    // 获取所有学习日期并去重排序
    const studyDates = [...new Set(studyRecords.map(record => record.date))].sort((a, b) => new Date(b) - new Date(a));
    
    let consecutiveDays = 0;
    const today = new Date();
    
    for (let i = 0; i < studyDates.length; i++) {
      const studyDate = new Date(studyDates[i]);
      const expectedDate = new Date(today);
      expectedDate.setDate(today.getDate() - i);
      
      // 检查日期是否连续
      if (this.isSameDay(studyDate, expectedDate)) {
        consecutiveDays++;
      } else {
        break;
      }
    }
    
    return consecutiveDays;
  },

  // 判断是否为同一天
  isSameDay: function(date1, date2) {
    return date1.getFullYear() === date2.getFullYear() &&
           date1.getMonth() === date2.getMonth() &&
           date1.getDate() === date2.getDate();
  },

  // 跳转到学习页面
  goToStudy: function() {
    wx.navigateTo({
      url: '/pages/word-study/word-study'
    });
  },

  // 创建测试数据
  createTestData: function() {
    const testRecords = [];
    const now = new Date();
    
    // 创建3条测试记录
    for (let i = 0; i < 3; i++) {
      const testDate = new Date(now);
      testDate.setDate(now.getDate() - i);
      
      const wordsLearned = 5 + i * 2;
      const correctRate = 80 + i * 5;
      const duration = 3 + i;
      
      const record = {
        timestamp: testDate.toISOString(),
        date: this.formatDateForDisplay(testDate),
        time: this.formatTimeForDisplay(testDate),
        wordsLearned: wordsLearned,
        correctRate: correctRate,
        duration: duration,
        details: `学习了${wordsLearned}个单词，正确${Math.round(wordsLearned * correctRate / 100)}个，错误${wordsLearned - Math.round(wordsLearned * correctRate / 100)}个`,
        words: []
      };
      
      testRecords.push(record);
    }
    
    wx.setStorageSync('studyRecords', testRecords);
    this.loadStudyRecords();
  },

  // 格式化显示日期
  formatDateForDisplay: function(date) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const today = new Date();
    const yesterday = new Date(today);
    yesterday.setDate(today.getDate() - 1);
    
    if (this.isSameDay(date, today)) {
      return '今天';
    } else if (this.isSameDay(date, yesterday)) {
      return '昨天';
    } else {
      return `${year}年${month}月${day}日`;
    }
  },

  // 格式化显示时间
  formatTimeForDisplay: function(date) {
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    return `${month}月${day}日 ${hour}:${minute.toString().padStart(2, '0')}`;
  },

  // 返回上一页
  goBack: function() {
    wx.navigateBack();
  }
}); 